package cn.com.member.controller.bonus;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import cn.com.api.entity.*;
import cn.com.api.service.*;

import cn.com.util.DateUtil;
import cn.com.util.JsonUtil;
import cn.com.util.Util;
import cn.com.util.Utils;

/**
 * 红包控制器
 */
@Controller
@RequestMapping
public class BonusController {

	private static Logger logger = Logger.getLogger(BonusController.class);

	@Autowired
	private ApiU_bonusService apiU_bonusService;
	@Autowired
	private ApiU_advertService apiU_advertService;
	@Autowired
	private ApiU_advert_resourceService apiU_advert_resourceService;
	@Autowired
	private ApiT_member_entrepreneurService apiT_member_entrepreneurService;
	@Autowired
	private U_labelService labelService;
	@Autowired
	private ApiU_stat_keywordsService apiU_stat_keywordsService;
	@Autowired
	private ApiT_enumsService apiT_enumsService;

	/**
	 * 红包广告列表
	 * 
	 * @return
	 */
	@RequestMapping(value = "bonus-list")
	public ModelAndView bonus_list(HttpServletRequest request, HttpServletResponse response) throws Exception {
		ApiTmember apiTmember = (ApiTmember) request.getSession().getAttribute("webuser");
		ModelAndView mv = new ModelAndView("/red/packets/packets-list");
		Map<String, Object> map = new HashMap<String, Object>();
		ApiT_member_entrepreneur apiT_member_entrepreneur = apiT_member_entrepreneurService
				.getEntrepreneurIdByUserId(apiTmember.getCid());
		map.put("ent_id", apiT_member_entrepreneur.getId());
		map.put("position_id", "3");// 全品红包和推荐红包
		// map.put("user_id", apiTmember.getCid());
		List<ApiU_bonus> bonuslist = apiU_bonusService.findBonusByMap(map);
		mv.addObject("bonuslist", bonuslist);
		return mv;
	}

	/**
	 * 喊个红包广告列表
	 * 
	 * @return
	 */
	@RequestMapping(value = "hanbonus-list")
	public ModelAndView hanbonus_list(HttpServletRequest request, HttpServletResponse response) throws Exception {
		ApiTmember apiTmember = (ApiTmember) request.getSession().getAttribute("webuser");
		ModelAndView mv = new ModelAndView("/red/packets/hanpackets-list");
		Map<String, Object> map = new HashMap<String, Object>();
		ApiT_member_entrepreneur apiT_member_entrepreneur = apiT_member_entrepreneurService
				.getEntrepreneurIdByUserId(apiTmember.getCid());
		map.put("ent_id", apiT_member_entrepreneur.getId());
		map.put("position_id", 17);// 喊个红包
		// map.put("user_id", apiTmember.getCid());
		List<ApiU_bonus> bonuslist = apiU_bonusService.findBonusByMap(map);
		mv.addObject("bonuslist", bonuslist);
		return mv;
	}

	/**
	 * 跳转到红包广告添加或修改页面
	 * 
	 * @param type
	 *            1-全品红包 2-推荐红包 3-喊个红包
	 * @return
	 */
	@RequestMapping("advert_bonusadvert-addOrUpdate")
	public ModelAndView advert_bonusadvert_addOrUpdate(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		ModelAndView mv = new ModelAndView("/red/packets/packets-insert");
		String bonus_id = request.getParameter("id");

		String type = request.getParameter("type");
		if (bonus_id != null && !"".equals(bonus_id)) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("id", bonus_id);
			List<ApiU_bonus> bonuslist = apiU_bonusService.findBonusByMap(map);
			ApiU_bonus apiU_bonus = bonuslist.get(0);
			ApiU_advert advert = apiU_bonus.getAdvert();
			if (advert.getPosition_id() == 3) {// 红包（推荐和全品）
				if (apiU_bonus.getAdvert().getInterest_key() != null
						&& !"".equals(apiU_bonus.getAdvert().getInterest_key())) {
					type = "2";
				} else {
					type = "1";
				}
			} else if (advert.getPosition_id() == 17) {// 喊个红包
				type = "3";
				String[] keywords = advert.getInterest_key().split(":");
				mv.addObject("keywords", keywords);
			}

			if (apiU_bonus != null) {// 将地区信息组成空间需要的格式数组
				String province = apiU_bonus.getAdvert().getProvince();
				String city = apiU_bonus.getAdvert().getCity();
				String area = apiU_bonus.getAdvert().getArea();
				if (province != null && !"".equals(province)) {
					String[] provinces = province.split(":");
					String[] citys = city.split(":");
					String[] areas = area.split(":");
					List<String> regions = new ArrayList<String>();
					for (int i = 0; i < provinces.length; i++) {
						regions.add(provinces[i] + "/" + citys[i] + "/" + areas[i]);
					}
					mv.addObject("regions", regions);
				}
			}
			mv.addObject("bonus", bonuslist.get(0));
		}
		String position_id = "";
		if ("3".equals(type)) {
			position_id = "17";
		} else {
			position_id = "3";
		}
		mv.addObject("position_id", position_id);
		mv.addObject("type", type);
		if ("2".equals(type)) {// 推荐红包，加载推荐信息项
			// 年龄区间字典
			List<ApiT_enums> agerange = apiT_enumsService.findT_enumssByItem_key("agerange");
			List<ApiT_enums> ageranges = apiT_enumsService.findT_enumssByParent_id(agerange.get(0).getId() + "");
			mv.addObject("ageranges", ageranges);

			// 职业字典
			List<ApiT_enums> profession = apiT_enumsService.findT_enumssByItem_key("profession");
			List<ApiT_enums> professions = apiT_enumsService.findT_enumssByParent_id(profession.get(0).getId() + "");
			mv.addObject("professions", professions);

			// 获取兴趣爱好标签库
			List<U_label> alllabels = labelService.getAlllabels(1);
			mv.addObject("alllabels", alllabels);
		}
		return mv;
	}

	/**
	 * 添加红包信息
	 * 
	 * @return
	 */
	@RequestMapping(value = "bonus-add")
	public void bonus_add(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		ApiTmember apiTmember = (ApiTmember) request.getSession().getAttribute("webuser");
		ApiT_member_entrepreneur apiT_member_entrepreneur = apiT_member_entrepreneurService
				.getEntrepreneurIdByUserId(apiTmember.getCid());
		map.clear();
		if (apiTmember.getVerify_entrepreneur() != 1) {
			map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
			map.put(Utils.MESSAGE, "用户不是企业主！");
		} else {
			// 红包id，判读是添加还是修改
			String bonusid = request.getParameter("id");
			// 广告的type 图片还是视频
			String resource_type = request.getParameter("resource_type");
			// 3为红包广告；17喊个红包
			String position_id = request.getParameter("position_id");
			// 投放区域 1-地区；0-全国
			String isarea = request.getParameter("isarea");
			// 地区信息 格式：江苏省/常州市/溧阳市
			String province = "";
			String city = "";
			String area = "";
			if (isarea != null && !"0".equals(isarea)) {
				String[] regioninfos = request.getParameterValues("regioninfo");
				for (String regioninfo : regioninfos) {
					if (regioninfo != null && !"".equals(regioninfo.trim())) {
						String[] regions = regioninfo.split("/");
						province += ":" + regions[0];
						if (regions.length >= 2) {
							city += ":" + regions[1];
						}
						if (regions.length >= 3) {
							area += ":" + regions[2];
						}
					}
				}
			}
			if (!"".equals(province)) {
				province = province.substring(1);
			}
			if (!"".equals(city)) {
				city = city.substring(1);
			}
			if (!"".equals(area)) {
				area = area.substring(1);
			}

			// 如果是喊个红包，则是关键字集合
			String[] keyword = request.getParameterValues("keyword");
			String keywords = Utils.arrayToStr(keyword, ":");

			// 经纬度及范围
			String longitude = request.getParameter("longitude");
			String latitude = request.getParameter("latitude");
			String distance_range = request.getParameter("distance_range");
			// 投放时间单位天
			String sign_term = request.getParameter("sign_term");
			// 投放总额
			String total_amount = request.getParameter("total_amount");
			// 实际点击次数（有金额红包数量）
			String count_charge = request.getParameter("count_charge");
			// 显示次数（总红包数量） （无红包数量为2者相差）
			String count = request.getParameter("count");
			// 广告标题
			String adv_name = request.getParameter("adv_name");
			// 缩略图
			String covers = request.getParameter("covers");
			// 广告轮播图
			String[] resources = request.getParameterValues("resources");
			// 视频地址
			String videoresource = request.getParameter("videoresource");
			// 祝福语
			String bless_word = request.getParameter("bless_word");
			// 年龄段
			String age_range = request.getParameter("age_range");
			// 职业
			String job_title = request.getParameter("job_title");
			// 兴趣关键字
			String[] labels = request.getParameterValues("label");
			String interest_key = "";
			if (labels != null && labels.length > 0) {
				interest_key = Util.join(":", labels);
			}

			if (bonusid == null || "".equals(bonusid)) {// 添加
				// 插入广告对应的红包
				ApiU_bonus u_bonus = new ApiU_bonus();
				// 平台收取的管理费
				BigDecimal platform_charge = new BigDecimal(total_amount).multiply(new BigDecimal("0.3"));
				// 红包金额为投资总额减去管理费
				u_bonus.setSummy(new BigDecimal(total_amount).subtract(platform_charge));
				u_bonus.setTitle(adv_name);
				u_bonus.setAdd_time(DateUtil.nowTimeToString());
				u_bonus.setIs_expire(0);
				u_bonus.setUser_id(apiTmember.getCid() + "");
				if ("0".equals(resource_type)) {
					u_bonus.setType(1);
				} else { // 视频广告时，广告的缩略图地址为视频的地址
					u_bonus.setType(2);
				}
				u_bonus.setDuring_time(0);

				u_bonus.setCount_charge(Integer.valueOf(count_charge));
				u_bonus.setCount_free(Integer.valueOf(count) - Integer.valueOf(count_charge));
				u_bonus.setCount(Integer.valueOf(count));
				u_bonus.setShow_times(0);
				// 投放地区只有一个城市时，定位数据才有用

				if (province.split(":").length == 1) {
					u_bonus.setLongitude(longitude);
					u_bonus.setLatitude(latitude);
				}

				u_bonus.setBless_word(bless_word);

				// 算法待定
				u_bonus.setMax_money(new BigDecimal("240"));
				u_bonus.setMin_money(new BigDecimal("0.01"));

				int ret_boolen = apiU_bonusService.U_bonusInsertion(u_bonus);

				if (ret_boolen > 0) {
					ApiU_advert u_advert = new ApiU_advert();
					u_advert.setAdv_name(u_bonus.getTitle());
					u_advert.setZan_count(0);
					u_advert.setPosition_id(Integer.valueOf(position_id));
					u_advert.setAdd_time(u_bonus.getAdd_time());
					u_advert.setProvince(province);
					u_advert.setCity(city);
					u_advert.setArea(area);
					u_advert.setStatus(0);
					u_advert.setIs_pay(0);
					u_advert.setPlatform_charge(platform_charge);
					// 投放地区只有一个城市时，定位数据才有用
					if ("".equals(province)) {// 全国
						u_advert.setDistance_range(0L);
						u_advert.setLongitude(null);
						u_advert.setLatitude(null);
					} else {
						if (province.split(":").length == 1) {
							u_advert.setLongitude(longitude);
							u_advert.setLatitude(latitude);
							if (distance_range != null && !"".equals(distance_range)) {
								u_advert.setDistance_range(Long.valueOf(distance_range));
							}
						}
					}

					if ("17".equals(position_id)) {// 喊个红包
						u_advert.setInterest_key(keywords);
					} else {
						u_advert.setSign_term(Integer.valueOf(sign_term));
					}
					/**************** 不为空则是推荐红包广告 ******************/
					if (interest_key != null && !"".equals(interest_key.trim())) {
						u_advert.setInterest_key(interest_key.trim());
					}

					if (age_range != null && !"".equals(age_range.trim())) {
						u_advert.setAge_range(age_range.trim());
					}

					if (job_title != null && !"".equals(job_title.trim())) {
						u_advert.setJob_title(job_title.trim());
					}
					/****************************************************/

					u_advert.setEnt_id(apiT_member_entrepreneur.getId() + "");// 企业id
					u_advert.setAdd_uid(apiTmember.getCid().toString());// 发布人id
					u_advert.setLogo(apiT_member_entrepreneur.getLogo_img());

					u_advert.setResource_type(Integer.valueOf(resource_type));
					u_advert.setTotal_amount(new BigDecimal(total_amount));
					u_advert.setShow_times(0);
					u_advert.setBonus_id(u_bonus.getId() + "");

					if ("1".equals(resource_type)) {// 视频广告时，广告的缩略图地址为视频的地址
						u_advert.setCovers(videoresource);
					} else {
						u_advert.setCovers(covers);
					}
					apiU_advertService.U_advertInsertion(u_advert);
					Integer adv_id = u_advert.getId();
					// 插入广告轮播图
					if ("0".equals(resource_type)) {// 图片广告
						for (int i = 0; i < resources.length; i++) {
							if (resources[i].length() > 0) {
								ApiU_advert_resource u_advert_resource = new ApiU_advert_resource();
								u_advert_resource.setAdvert_id(adv_id.toString());
								u_advert_resource.setResource_url(resources[i]);
								u_advert_resource.setSort(i + 1);
								apiU_advert_resourceService.insertU_advert_resource(u_advert_resource);
							}
						}
					} else {// 视频广告
						ApiU_advert_resource u_advert_resource = new ApiU_advert_resource();
						u_advert_resource.setAdvert_id(adv_id.toString());
						u_advert_resource.setResource_url(videoresource);
						apiU_advert_resourceService.insertU_advert_resource(u_advert_resource);
					}
					map.put(Utils.DATAS, adv_id);
				}
			} else {// 修改
				map.clear();
				map.put("id", bonusid);
				List<ApiU_bonus> bonuslist = apiU_bonusService.findBonusByMap(map);
				map.clear();
				// 跟新红包信息
				ApiU_bonus apiU_bonus = bonuslist.get(0);
				apiU_bonus.setTitle(adv_name);
				if (province.split(":").length == 1) {
					apiU_bonus.setLongitude(longitude);
					apiU_bonus.setLatitude(latitude);
				} else {
					apiU_bonus.setLongitude(null);
					apiU_bonus.setLatitude(null);
				}
				apiU_bonus.setBless_word(bless_word);
				apiU_bonusService.updateU_bonus(apiU_bonus);

				// 修改广告信息
				ApiU_advert advert = apiU_bonus.getAdvert();

				advert.setAdv_name(apiU_bonus.getTitle());
				advert.setProvince(province);
				advert.setCity(city);
				advert.setArea(area);
				if ("".equals(province)) {// 全国
					advert.setDistance_range(0L);
					advert.setLongitude(null);
					advert.setLatitude(null);
				} else {
					if (province.split(":").length == 1) {
						advert.setLongitude(longitude);
						advert.setLatitude(latitude);
						if (distance_range != null && !"".equals(distance_range)) {
							advert.setDistance_range(Long.valueOf(distance_range));
						} else {
							advert.setDistance_range(0L);
						}
					} else {
						advert.setLongitude(null);
						advert.setLatitude(null);
						advert.setDistance_range(0L);
					}
				}

				if ("17".equals(position_id)) {// 喊个红包
					advert.setInterest_key(keywords);
				}

				if (interest_key != null && !"".equals(interest_key.trim())) {
					advert.setInterest_key(interest_key.trim());
				}

				if (age_range != null && !"".equals(age_range.trim())) {
					advert.setAge_range(age_range.trim());
				}

				if (job_title != null && !"".equals(job_title.trim())) {
					advert.setJob_title(job_title.trim());
				}

				if (advert.getResource_type() == 1) {// 视频广告时，广告的缩略图地址为视频的地址
					advert.setCovers(videoresource);
				} else {
					advert.setCovers(covers);
				}

				// 如果是驳回状态修改后重新提交审核
				if (advert.getStatus() == 3) {
					advert.setStatus(0);// 修改为待审核状态
					advert.setExt1(null);// 清空驳回原因
				}

				apiU_advertService.updateU_advert(advert);
				// 更新资源
				Integer adv_id = advert.getId();
				apiU_advert_resourceService.deleteAdvertResource(adv_id);
				// 插入广告轮播图
				if (advert.getResource_type() == 0) {// 图片广告
					for (int i = 0; i < resources.length; i++) {
						if (resources[i].length() > 0) {
							ApiU_advert_resource u_advert_resource = new ApiU_advert_resource();
							u_advert_resource.setAdvert_id(adv_id.toString());
							u_advert_resource.setResource_url(resources[i]);
							u_advert_resource.setSort(i + 1);
							apiU_advert_resourceService.insertU_advert_resource(u_advert_resource);
						}
					}
				} else {// 视频广告
					ApiU_advert_resource u_advert_resource = new ApiU_advert_resource();
					u_advert_resource.setAdvert_id(adv_id.toString());
					u_advert_resource.setResource_url(videoresource);
					apiU_advert_resourceService.insertU_advert_resource(u_advert_resource);
				}
			}
			map.put(Utils.MESSAGE, "操作成功！");
			map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
		}

		JsonUtil.printJson(response, JsonUtil.object2json(map));
	}

	/**
	 * 跳转到喊个红包添加或修改页面
	 * 
	 * @param type
	 *            1-全品红包 2-推荐红包
	 * @return
	 */
	@RequestMapping("hanbonusadvert-addOrUpdate")
	public ModelAndView hanbonusadvert_addOrUpdate(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		ModelAndView mv = new ModelAndView("/red/packets/packets-insert");
		String bonus_id = request.getParameter("id");
		String type = request.getParameter("type");
		if (bonus_id != null && !"".equals(bonus_id)) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("id", bonus_id);
			List<ApiU_bonus> bonuslist = apiU_bonusService.findBonusByMap(map);
			ApiU_bonus apiU_bonus = bonuslist.get(0);
			if (apiU_bonus.getAdvert().getInterest_key() != null
					&& !"".equals(apiU_bonus.getAdvert().getInterest_key())) {
				type = "2";
			} else {
				type = "1";
			}
			if (apiU_bonus != null) {// 将地区信息组成空间需要的格式数组
				String province = apiU_bonus.getAdvert().getProvince();
				String city = apiU_bonus.getAdvert().getCity();
				String area = apiU_bonus.getAdvert().getArea();
				String[] provinces = province.split(":");
				String[] citys = city.split(":");
				String[] areas = area.split(":");
				List<String> regions = new ArrayList<String>();
				for (int i = 0; i < provinces.length; i++) {
					regions.add(provinces[i] + "/" + citys[i] + "/" + areas[i]);
				}
				mv.addObject("regions", regions);
			}
			mv.addObject("bonus", bonuslist.get(0));
		}
		mv.addObject("type", type);

		if ("2".equals(type)) {// 推荐红包，加载推荐信息项
			// 年龄区间字典
			List<ApiT_enums> agerange = apiT_enumsService.findT_enumssByItem_key("agerange");
			List<ApiT_enums> ageranges = apiT_enumsService.findT_enumssByParent_id(agerange.get(0).getId() + "");
			mv.addObject("ageranges", ageranges);

			// 职业字典
			List<ApiT_enums> profession = apiT_enumsService.findT_enumssByItem_key("profession");
			List<ApiT_enums> professions = apiT_enumsService.findT_enumssByParent_id(profession.get(0).getId() + "");
			mv.addObject("professions", professions);

			// 获取兴趣爱好标签库
			List<U_label> alllabels = labelService.getAlllabels(1);
			mv.addObject("alllabels", alllabels);
		}
		return mv;
	}

	/**
	 * 软删除
	 * 
	 * @return
	 */
	@RequestMapping(value = "bonus-delete")
	public void bonusdelete(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			String bonusid = request.getParameter("bonusid");
			apiU_bonusService.deleteBonus(Integer.valueOf(bonusid));
			map.put(Utils.MESSAGE, "添加成功！");
			map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			map.put(Utils.RESULT, Utils.RESULT_RC_EXCEPTION);
			map.put(Utils.MESSAGE, "系统异常");
		}
		JsonUtil.printJson(response, JsonUtil.object2json(map));
	}

	/**
	 * 喊红包已喊关键字的统计
	 * 
	 * @return
	 */
	@RequestMapping(value = "keywordsCount")
	public ModelAndView keywordsCount(HttpServletRequest request, HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView("/red/packets/keywordscount");
		try {
			List<ApiU_stat_keywords> apiU_stat_keywords = apiU_stat_keywordsService.keywordsCount();
			mv.addObject("apiU_stat_keywords", apiU_stat_keywords);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return mv;
	}

}
